import { network } from "../../utils/network.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    islyric: true,
    isPlayMusic: false,
    id: 0,
    time1: "00:00",
    time2: "00:00",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id;

    that.setData({
      id: id,
    })

    if (id == 12) {
      
    }

    wx.getStorage({
      key: 'played',
      success: function (res) {
        that.setData({
          histories: res.data,
        })
      },
    })

    network.getDetail({
      id: id,
      success: function (song) {
        that.setData({
          song: song,
        })
      }
    })

    network.getLyric({
      id: id,
      success: function (lrc) {

        that.setData({
          lyric: lrc
        })
      },
    })


    network.getPlay({
      id: id,
      success: function (url) {
        that.setData({
          url: url
        })
      },
    })

    wx.getBackgroundAudioPlayerState({
      success(res) {
        const status = res.status
        const dataUrl = res.dataUrl
        const currentPosition = res.currentPosition
        const duration = res.duration
        const downloadPercent = res.downloadPercent
        that.setData({
          currentPosition: currentPosition,
          duration: duration
        })
      }
    })

    if (getApp().globalData.musicid === id) {
      that.setData({
        isPlayMusic: getApp().globalData.isPlayMusic
      })
    } else {
      that.setData({
        isPlayMusic: false
      })
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onmusictap: function () {
    var that = this;
    var id = that.data.id;
    if (that.data.isPlayMusic) {
      wx.pauseBackgroundAudio();
      console.log("stop")
    } else {

      wx.playBackgroundAudio({
        dataUrl: that.data.url,
        title: that.data.song.name,
        coverImgUrl: that.data.song.al.picUrl,
      });
      var app = getApp()
      app.globalData.musicid = that.data.id;

      var isExisted = false;
      for (var index = 0; index < getApp().globalData.playing.length; index++) {
        var savedid = getApp().globalData.playing[index];
        if (savedid.id == id) {
          isExisted = true
          break
        }
      }
      if (!isExisted) {
        getApp().globalData.playing.push({ id: id });
        console.log(getApp().globalData.playing)
        getApp().globalData.playno = getApp().globalData.playing.length
      }

      var histories = that.data.histories;
      if (histories) {
        for (var index = 0; index < histories.length; index++) {
          var savedid = histories[index];
          if (savedid.id == id) {
            histories.isExisted = true;
            histories.splice(index, 1)
            break;
          }
        }
      }
      if (!histories) {
        histories = [];
      }
      console.log(id)
      id = parseInt(id)
      histories.push({ id: id });
      wx.setStorage({
        key: 'played',
        data: histories,
        success: function (res) {
          console.log("保存成功")
          console.log(histories)
        }
      })

      console.log("play")
      let bgMusic = wx.getBackgroundAudioManager();
      bgMusic.onTimeUpdate(() => {
        this.setData({
          time: bgMusic.currentTime,
          alltime: bgMusic.duration,
          time1: this.timeToString(bgMusic.currentTime.toFixed(0)),
          time2: this.timeToString(bgMusic.duration.toFixed(0))
        })
      })
    }
    getApp().globalData.isPlayMusic = (!that.data.isPlayMusic)
    that.setData({
      isPlayMusic: (!that.data.isPlayMusic)
    })
  },
  onlyrictap: function () {
    var that = this
    that.setData({
      islyric: (!this.data.islyric)
    })
  },

  timeToString: function (duration) {

    let str = '';
    let minute = parseInt(duration / 60) < 10 ? ('0' + parseInt(duration / 60)) : (parseInt(duration / 60));

    let second = (duration % 60) < 10 ? ('0' + duration % 60) : (duration % 60);

    str = minute + ':' + second;

    return str;

  },

  sliceNull: function (lrc) {
    var result = []
    for (var i = 0; i < lrc.length; i++) {
      if (lrc[i][1] == "") {
      } else {
        result.push(lrc[i]);
      }
    }
    return result
  },

  parseLyric: function (text) {
    const result = [];
    var lines = text.split('\n'), //切割每一行
      pattern = /\[\d{2}:\d{2}.\d{2}\]/g
    //去掉不含时间的行
    while (!pattern.test(lines[0])) {
      lines = lines.slice(1);
    };
    //上面用'\n'生成数组时，结果中最后一个为空元素，这里将去掉
    lines[lines.length - 1].length === 0 && lines.pop();
    lines.forEach(function (v /*数组元素值*/, i /*元素索引*/, a /*数组本身*/) {
      //提取出时间[xx:xx.xx]
      var time = v.match(pattern),
        //提取歌词
        value = v.replace(pattern, '');
      // 因为一行里面可能有多个时间，所以time有可能是[xx:xx.xx][xx:xx.xx][xx:xx.xx]的形式，需要进一步分隔
      time.forEach(function (v1, i1, a1) {
        //去掉时间里的中括号得到xx:xx.xx
        var t = v1.slice(1, -1).split(':');
        //将结果压入最终数组
        result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
        console.log(result)
      });
    });
    //最后将结果数组中的元素按时间大小排序，以便保存之后正常显示歌词
    result.sort(function (a, b) {
      return a[0] - b[0];
    });
    return result;
  },


  playFun: function () {
    var that = this
    this.setData({
      lyric: that.sliceNull(that.parseLyric(that.data.lyric))
    })
  },

  last: function () {
    getApp().globalData.playno = getApp().globalData.playno - 1
    if (getApp().globalData.playno <= -1) {
      getApp().globalData.playno = getApp().globalData.playing.length - 1
    }
    this.onLoad({ id: 12, isPlayMusic: true })
  },

  next: function () {
    getApp().globalData.playno = getApp().globalData.playno + 1
    if (getApp().globalData.playno >= getApp().globalData.playing.length) {
      getApp().globalData.playno = 0
    }
    this.onLoad({ id: 12, isPlayMusic: true })
  }
})